﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Text;

namespace DAO
{
    public class FriendRequestDAO
    {
        private WebChatDBEntities db = new WebChatDBEntities();

        public FriendRequest GetFriendRequest(int userId)
        {
            FriendRequest request = db.FriendRequests.FirstOrDefault(r => r.ToUserId == userId);

            return request;
        }

        public void AddFriendRequest(int userId, string friendName)
        {
            var user = db.Users.Find(userId);
            var friend = db.Users.SingleOrDefault(u => u.UserName.Equals(friendName));

            if(user != null && friend != null)
            {
                FriendRequest request = new FriendRequest
                                        {
                                            UserId = user.Id,
                                            ToUserId = friend.Id
                                        };
                db.FriendRequests.Add(request);
                db.SaveChanges();
            }         
        }

        public bool DeleteFriendRequest(int userId, string friendName)
        {
            var user = db.Users.Find(userId);
            var friend = db.Users.SingleOrDefault(u => u.UserName.Equals(friendName));

            if (user != null && friend != null)
            {
                FriendRequest request =
                    db.FriendRequests.FirstOrDefault(r => r.UserId == friend.Id && r.ToUserId == user.Id);
                db.FriendRequests.Remove(request);

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return false;
                }
            }

            return true;
        }
    }
}
